#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

#ifndef STASSID
#define STASSID "HONOR-0315MY"
#define STAPSK "dist@123,."
#endif

const char* ssid = STASSID;
const char* password = STAPSK;

// 电脑的MAC地址
byte mac[] = { 0xC8, 0x7F, 0x54, 0x6F, 0xD0, 0x83 };

ESP8266WebServer server(80);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot); // 主页
  server.on("/wake", handleWake); // 唤醒
  server.on("/shutdown", handleShutdown); // 关机
  server.on("/reboot", handleReboot); // 重启
  server.on("/sleep", handleSleep); // 睡眠

  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

void handleRoot() {
  String html = "<!DOCTYPE html>\n" 
            "<html>\n" 
            "<head>\n" 
            "    <meta charset=\"UTF-8\" />\n" 
            "    <title>重大决策遥控</title>\n" 
            "    <style>\n" 
            "        html body {\n" 
            "            display: flex;\n" 
            "            flex-direction: column;\n" 
            "            align-items: center;\n" 
            "            background: #615f5f;\n" 
            "            font-family: Arial, sans-serif;\n" 
            "            font-size: 30px;\n" 
            "            margin: 0;\n" 
            "            padding: 0;\n" 
            "            touch-action: manipulation;\n" 
            "            user-scalable: no;\n" 
            "        }\n" 
            "\n" 
            "        .remote {\n" 
            "            min-width: 80%;\n" 
            "            height: 90vh;\n" 
            "            background: #333;\n" 
            "            padding: 20px;\n" 
            "            border-radius: 15px;\n" 
            "            box-shadow: 0 5px 15px rgba(0,0,0,0.3);\n" 
            "        }\n" 
            "\n" 
            "        .d-pad {\n" 
            "            display: grid;\n" 
            "            grid-template-columns: repeat(3, 1fr);\n" 
            "            gap: 5px;\n" 
            "        }\n" 
            "\n" 
            "\n" 
            "        .button-circle {\n" 
            "            display: flex;\n" 
            "            justify-content: center;\n" 
            "            align-items: center;\n" 
            "            background: #444;\n" 
            "            color: white;\n" 
            "            border: none;\n" 
            "            border-radius: 50%;\n" 
            "            padding: 15px;\n" 
            "            cursor: pointer;\n" 
            "            transition: all 0.2s;\n" 
            "            user-select: none;\n" 
            "            width: 100px;\n" 
            "            height: 100px;\n" 
            "        }\n" 
            "\n" 
            "        .button {\n" 
            "            display: flex;\n" 
            "            justify-content: center;\n" 
            "            align-items: center;\n" 
            "            background: #444;\n" 
            "            color: white;\n" 
            "            border: none;\n" 
            "            border-radius: 8px;\n" 
            "            padding: 15px;\n" 
            "            cursor: pointer;\n" 
            "            transition: all 0.2s;\n" 
            "            user-select: none;\n" 
            "            width: 90px;\n" 
            "            height: 56px;\n" 
            "        }\n" 
            "\n" 
            "        .width-full {\n" 
            "            width: auto;\n" 
            "        }\n" 
            "\n" 
            "        .button:active {\n" 
            "            background: #666;\n" 
            "            transform: scale(0.95);\n" 
            "        }\n" 
            "\n" 
            "        .center-btn {\n" 
            "            grid-column: 2;\n" 
            "            grid-row: 2;\n" 
            "            background: #555;\n" 
            "        }\n" 
            "\n" 
            "        .func-buttons {\n" 
            "            display: flex;\n" 
            "            justify-content: space-between;\n" 
            "            gap: 10px;\n" 
            "            padding: 30px;\n" 
            "        }\n" 
            "\n" 
            "        .func-btn {\n" 
            "            background: #666;\n" 
            "            padding: 10px 15px;\n" 
            "        }\n" 
            "\n" 
            "        #info {\n" 
            "            margin: 20px;\n" 
            "            padding: 20px;\n" 
            "            background: rgba(134, 183, 104, 0.606);\n" 
            "            border-radius: 5px;\n" 
            "            min-width: 80%;\n" 
            "            text-align: center;\n" 
            "            font-weight: bold;\n" 
            "            color: #EEE;\n" 
            "        }\n" 
            "\n" 
            "        .power {\n" 
            "            background: #d9534f;\n" 
            "        }\n" 
            "\n" 
            "        .confirm {\n" 
            "            background: #5cb85c;\n" 
            "        }\n" 
            "\n" 
            "        .about {\n" 
            "            text-align: center;\n" 
            "            color: #FFF;\n" 
            "            font-size: 2rem;\n" 
            "            width: 100%;\n" 
            "            margin-top: 30px;\n" 
            "        }\n" 
            "    </style>\n" 
            "</head>\n" 
            "<body style=\"width: 100%; height: 100%;\">\n" 
            "    <div id=\"info\">功能涉及国家重大决策, 必须征得总统同意后使用!</div>\n" 
            "    <div class=\"remote\">\n" 
            "        <div class=\"func-buttons\">\n" 
            "            <div class=\"button-circle func-btn\" data-key=\"PowerSaving\">省电</div>\n" 
            "            <div class=\"button-circle func-btn power\" data-key=\"Power\">开机</div>\n" 
            "        </div>\n" 
            "        <div class=\"func-buttons\">\n" 
            "            <div class=\"button func-btn\" data-key=\"Collect\">收藏</div>\n" 
            "            <div class=\"button func-btn\" data-key=\"Offline\">断网</div>\n" 
            "            <div class=\"button func-btn\" data-key=\"Setting\">设置</div>\n" 
            "        </div>\n" 
            "        <div class=\"d-pad\">\n" 
            "            <div class=\"button width-full\" data-key=\"BrightnessUp\">亮度 -</div>\n" 
            "            <div class=\"button width-full\" data-key=\"ArrowUp\">↑</div>\n" 
            "            <div class=\"button width-full\" data-key=\"BrightnessDown\">亮度 +</div>\n" 
            "            <div class=\"button width-full\" data-key=\"ArrowLeft\">←</div>\n" 
            "            <div class=\"button width-full center-btn\" data-key=\"Enter\">OK</div>\n" 
            "            <div class=\"button width-full\" data-key=\"ArrowRight\">→</div>\n" 
            "            <div class=\"button width-full\" data-key=\"VolumeUp\">音量 -</div>\n" 
            "            <div class=\"button width-full\" data-key=\"ArrowDown\">↓</div>\n" 
            "            <div class=\"button width-full\" data-key=\"VolumeDown\">音量 +</div>\n" 
            "        </div>\n" 
            "        <div class=\"func-buttons\">\n" 
            "            <div class=\"button func-btn\" data-key=\"light\">灯炮</div>\n" 
            "            <div class=\"button func-btn\" data-key=\"Camera\">摄像头</div>\n" 
            "            <div class=\"button func-btn\" data-key=\"Socket\">插座</div>\n" 
            "        </div>\n" 
            "        <div class=\"d-pad\">\n" 
            "            <div class=\"button width-full\" data-key=\"one\">1</div>\n" 
            "            <div class=\"button width-full\" data-key=\"two\">2</div>\n" 
            "            <div class=\"button width-full\" data-key=\"three\">3</div>\n" 
            "            <div class=\"button width-full\" data-key=\"four\">4</div>\n" 
            "            <div class=\"button width-full\" data-key=\"five\">5</div>\n" 
            "            <div class=\"button width-full\" data-key=\"six\">6</div>\n" 
            "            <div class=\"button width-full\" data-key=\"seven\">7</div>\n" 
            "            <div class=\"button width-full\" data-key=\"eight\">8</div>\n" 
            "            <div class=\"button width-full\" data-key=\"nine\">9</div>\n" 
            "            <div class=\"button width-full\" data-key=\"nine\">*</div>\n" 
            "            <div class=\"button width-full\" data-key=\"zero\">0</div>\n" 
            "            <div class=\"button width-full\" data-key=\"nine\">#</div>\n" 
            "        </div>\n" 
            "        <div class=\"func-buttons\">\n" 
            "            <div class=\"button func-btn\" data-key=\"IceBox\">冰箱</div>\n" 
            "            <div class=\"button func-btn\" data-key=\"Curtain\">窗帘</div>\n" 
            "            <div class=\"button func-btn\" data-key=\"TV\">电视</div>\n" 
            "        </div>\n" 
            "        <div class=\"func-buttons\">\n" 
            "            <div class=\"button func-btn\" data-key=\"Washer\">洗衣机</div>\n" 
            "            <div class=\"button func-btn\" data-key=\"Sweeper\">扫地机</div>\n" 
            "            <div class=\"button func-btn\" data-key=\"Humidifier\">加湿器</div>\n" 
            "        </div>\n" 
            "        <div class=\"about\">©copyright 2025 power by YIueil</div>\n" 
            "    </div>\n" 
            "    <script>\n" 
            "        const buttons = document.querySelectorAll('.button, .button-circle');\n" 
            "        const info = document.getElementById('info');\n" 
            "        // 按钮点击处理\n" 
            "        buttons.forEach(button => {\n" 
            "            button.addEventListener('click', () => {\n" 
            "                const key = button.dataset.key;\n" 
            "                showFeedback(key);\n" 
            "            });\n" 
            "        });\n" 
            "        function showFeedback(key) {\n" 
            "            const keyNames = {\n" 
            "                Power: {\n" 
            "                    name: '总电源',\n" 
            "                    info: '总电源已打开',\n" 
            "                    method: '/wake'\n" 
            "                },\n" 
            "                PowerSaving: {\n" 
            "                    name: '省电开关',\n" 
            "                    info: '已开启省电',\n" 
            "                    method: '/shutdown'\n" 
            "                }\n" 
            "            };\n" 
            "            const target = keyNames[key]\n" 
            "            info.textContent = target?.info || '功能待开发'\n" 
            "            info.style.animation = 'none';\n" 
            "            void info.offsetWidth; // 触发重绘\n" 
            "            info.style.animation = 'highlight 1.5s';\n" 
            "            if (target.method) {\n" 
            "                simpleAjax(\n" 
            "                    target.method,\n" 
            "                    'GET',\n" 
            "                    null, // 请求参数\n" 
            "                    function(response) {\n" 
            "                        console.log('Response:', response);\n" 
            "                    },\n" 
            "                    function(error) {\n" 
            "                        console.error('Error:', error);\n" 
            "                    }\n" 
            "                );\n" 
            "            }\n" 
            "        }\n" 
            "        // 动画\n" 
            "        const style = document.createElement('style');\n" 
            "        style.textContent = ` \n" 
            "            @keyframes highlight {\n" 
            "                0% { background: #615F5F; }\n" 
            "                100% { background: #779464; }\n" 
            "            }\n" 
            "        `;\n" 
            "        document.head.appendChild(style);\n" 
            "\n" 
            "        function simpleAjax(url, method, data, successCallback, errorCallback) {\n" 
            "            var xhr = new XMLHttpRequest();\n" 
            "            xhr.open(method, url, true);\n" 
            "            xhr.onload = function() {\n" 
            "                if (xhr.status >= 200 && xhr.status < 300) {\n" 
            "                    // 请求成功，调用成功回调函数\n" 
            "                    successCallback(xhr.responseText);\n" 
            "                } else {\n" 
            "                    // 请求失败，调用错误回调函数\n" 
            "                    errorCallback(xhr.statusText);\n" 
            "                }\n" 
            "            };\n" 
            "            xhr.onerror = function() {\n" 
            "                errorCallback(xhr.statusText);\n" 
            "            };\n" 
            "            if (data && typeof data === 'object') {\n" 
            "                xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');\n" 
            "                data = JSON.stringify(data);\n" 
            "            }\n" 
            "            xhr.send(data);\n" 
            "        }\n" 
            "    </script>\n" 
            "</body>\n" 
            "</html>";
  server.send(200, "text/html; charset=UTF-8", html);
}

void handleWake() {
  // 发送WOL包
  sendWOL();
  Serial.println("唤醒电脑");
  server.send(200, "text/plain", "唤醒信号已发送");
}

void handleShutdown() {
  // 这里应该有代码来远程关机，可能需要通过SSH或其他协议
  Serial.println("电脑关机");
  server.send(200, "text/plain", "关机命令已发送");
}

void handleReboot() {
  // 这里应该有代码来远程重启，可能需要通过SSH或其他协议
  Serial.println("电脑重启");
  server.send(200, "text/plain", "重启命令已发送");
}

void handleSleep() {
  // 这里可以放置代码来使电脑进入睡眠状态
  Serial.println("电脑睡眠");
  server.send(200, "text/plain", "睡眠命令已发送");
}

void sendWOL() {
  // 创建WOL包
  const int packetSize = 102;
  byte wolPacket[packetSize];

  // WOL包的魔术包部分
  for (int i = 0; i < 6; i++) {
    wolPacket[i] = 0xFF;
  }

  // 目标MAC地址重复16次
  for (int i = 1; i <= 16; i++) {
    for (int j = 0; j < 6; j++) {
      wolPacket[i * 6 + j] = mac[j];
    }
  }

  // 发送WOL包到广播地址
  WiFiUDP Udp;
  Udp.beginPacket(IPAddress(255, 255, 255, 255), 9);
  Udp.write(wolPacket, packetSize);
  Udp.endPacket();
}
